import copy
import datetime
import os
from fastapi import APIRouter
from pydantic import BaseModel

from app.core.standard import UnifyResponse
from app.core.standard import default_return_value

from app.core.config import mysql_client_path
from app.core.config import data_backup_path

from .basic_utils import run_cmd

router = APIRouter()


class ToBackupInfo(BaseModel):
    mysql_con_host: str
    mysql_con_port: int
    mysql_con_psw: str = None
    mysql_con_user: str = None
    database: str = None
    table_name: str = None  # 1: check 2: execute
    columns: list = []  # 0: 不备份 1: 备份
    backup_sql: str = None


@router.post(
    path="",
    name="SQL执行",
)
async def data_backup_handler(item: ToBackupInfo):
    mysql_con_host = item.mysql_con_host
    mysql_con_port = item.mysql_con_port
    mysql_con_user = item.mysql_con_user
    mysql_con_psw = item.mysql_con_psw
    database = item.database
    backup_sql = item.backup_sql
    # table_name = item.table_name
    # columns = item.columns
    if mysql_con_user is None:
        mysql_con_user = 'a_dba_rw'
    if mysql_con_psw is None:
        mysql_con_psw = get_password(mysql_con_host, mysql_con_port, mysql_con_user)
    backup_run_return_code, stdout, stderr = data_backup(mysql_con_host=mysql_con_host, mysql_con_port=mysql_con_port,
                                                         database=database, mysql_con_user=mysql_con_user,
                                                         mysql_con_psw=mysql_con_psw, backup_sql=backup_sql
                                                         )
    if backup_run_return_code != 0:
        # class UnifyResponse(BaseModel):
        #     status: int = 0
        #     result: int = 0
        #     data: Union[dict, str, list, None] = None
        #     extra_info: Union[dict, str, list, None] = None
        #     message: str = ''
        #     return_code: int = 0

        return UnifyResponse(status=1, message="备份失败", result=1, return_code=1, data=[stdout, stderr])
    else:
        return UnifyResponse(status=0, message="备份成功", result=0, return_code=0)


def get_password(mysql_con_host, mysql_con_port, mysql_con_user='a_dba_rw'):
    # return 'a_dba_rw', 'X5KL\!qm_WuD4wJ0T'
    return 'X5KL!qm_WuD4wJ0T'


def data_backup(**kwargs):
    # (mysql_con_host=mysql_con_host, mysql_con_port=mysql_con_port,
    # database=database, mysql_con_user=mysql_con_user,
    # mysql_con_psw=mysql_con_psw
    mysql_con_host = kwargs.get('mysql_con_host')
    mysql_con_port = kwargs.get('mysql_con_port')
    database = kwargs.get('database')
    mysql_con_user = kwargs.get('mysql_con_user')
    mysql_con_psw = kwargs.get('mysql_con_psw')
    backup_sql = kwargs.get('backup_sql')

    now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    # user_name, password = get_password()
    mysql_client = f'{mysql_client_path}/mysql'
    data_path = f"{data_backup_path}/{mysql_con_host}-{mysql_con_port}"
    if not os.path.exists(data_path):
        os.makedirs(data_path)

    backup_file = f"{data_path}/{database}-{now_time}.txt"
    mysql_backup_command = f'{mysql_client} -p{mysql_con_psw} --host={mysql_con_host} --port={mysql_con_port} ' \
                           f'-u{mysql_con_user} {database} -Ne "{backup_sql}" > {backup_file}'
    return run_cmd(mysql_backup_command)

    # if len(columns) == 0:
    #     select_sql = f"select * from {table_name};"
    #     mysql_backup_command = f'{mysql_client} -p{password} --host={mysql_host} --port={mysql_port} ' \
    #                            f'-u{user_name} {database_name} -Ne "{select_sql}" > {backup_file}'
    #     return run_cmd(mysql_backup_command)
